package com.lyfei.yd.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lyfei.yd.mapper.AddressMapper;
import com.lyfei.yd.domain.entity.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service("addressService")
public class AddressService extends BaseService<AddressMapper, Address> {
    @Autowired
    private RegionService regionService;

    public List<Address> getByUserId(Long userId) {
        return this.list(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getDeleted, 0));
    }

    public Address getDefaultByUserId(Long userId) {
        return this.getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDefault, 1)
                .eq(Address::getDeleted, 0));
    }

    public void setOtherAddressesToNotDefault(Long userId, Long currentAddressId) {
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Address::getIsDefault, false) // 设置isDefault为false
                .eq(Address::getUserId, userId) // 匹配userId
                .ne(currentAddressId != null, Address::getId, currentAddressId); // 排除当前地址，如果currentAddressId不为null

        this.update(null, updateWrapper); // 执行更新操作
    }

    public void fillAddressNames(Address address) {
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> address.setProvinceName(regionService.getById(address.getProvinceId()).getName())),
                CompletableFuture.runAsync(() -> address.setCityName(regionService.getById(address.getCityId()).getName())),
                CompletableFuture.runAsync(() -> address.setAreaName(regionService.getById(address.getAreaId()).getName()))
        ).join();
    }

    public void fillAddressNames(List<Address> addresses) {
        CompletableFuture.allOf(addresses.stream()
                .map(address -> CompletableFuture.allOf(
                        CompletableFuture.runAsync(() -> address.setProvinceName(regionService.getById(address.getProvinceId()).getName())),
                        CompletableFuture.runAsync(() -> address.setCityName(regionService.getById(address.getCityId()).getName())),
                        CompletableFuture.runAsync(() -> address.setAreaName(regionService.getById(address.getAreaId()).getName()))
                )).toArray(CompletableFuture[]::new)).join();
    }
}
